#!/usr/bin/env python3
"""
简单的时区转换测试
"""

from datetime import datetime
from typing import Dict, Any
import pytz
from pydantic import BaseModel, model_serializer


class SimpleBaseSchema(BaseModel):
    """简化的基础Schema用于测试"""

    @model_serializer
    def serialize_model(self) -> Dict[str, Any]:
        """Convert all datetime fields from UTC to Asia/Shanghai and format as 'YYYY-MM-DD HH:MM:SS'"""
        data = {}

        # Get China timezone
        china_tz = pytz.timezone('Asia/Shanghai')

        for field_name, field_value in self.__dict__.items():
            if isinstance(field_value, datetime):
                # Convert UTC to China timezone and format
                if field_value.tzinfo is None:
                    # Assume UTC if no timezone info
                    utc_time = pytz.UTC.localize(field_value)
                else:
                    utc_time = field_value.astimezone(pytz.UTC)

                china_time = utc_time.astimezone(china_tz)
                data[field_name] = china_time.strftime('%Y-%m-%d %H:%M:%S')
            else:
                data[field_name] = field_value

        return data


class TestModel(SimpleBaseSchema):
    """测试模型"""
    id: int
    name: str
    created_at: datetime
    updated_at: datetime


def test_timezone_conversion():
    """测试时区转换功能"""
    print("🧪 测试时区转换功能")

    # 创建UTC时间
    utc_now = datetime(2024, 1, 1, 12, 0, 0)  # UTC时间: 2024-01-01 12:00:00

    # 创建测试模型实例
    test_instance = TestModel(
        id=1,
        name="测试用户",
        created_at=utc_now,
        updated_at=utc_now
    )

    # 序列化模型（这会触发时区转换）
    serialized = test_instance.model_dump()

    print(f"原始UTC时间: {utc_now}")
    print(f"转换后created_at: {serialized['created_at']}")
    print(f"转换后updated_at: {serialized['updated_at']}")

    # 验证结果
    expected_format = "2024-01-01 20:00:00"  # UTC+8应该是20:00:00
    if serialized['created_at'] == expected_format:
        print("✅ 时区转换成功！UTC 12:00:00 正确转换为东八区 20:00:00")
        return True
    else:
        print(f"❌ 时区转换失败！期望: {expected_format}, 实际: {serialized['created_at']}")
        return False


def test_with_timezone_aware():
    """测试带时区信息的datetime转换"""
    print("\n🧪 测试带时区信息的datetime转换")

    # 创建带UTC时区信息的时间
    utc_tz = pytz.UTC
    utc_time_with_tz = utc_tz.localize(datetime(2024, 6, 15, 14, 30, 0))  # UTC时间带时区信息

    test_instance = TestModel(
        id=2,
        name="带时区测试",
        created_at=utc_time_with_tz,
        updated_at=utc_time_with_tz
    )

    serialized = test_instance.model_dump()

    print(f"原始UTC时间(带时区): {utc_time_with_tz}")
    print(f"转换后created_at: {serialized['created_at']}")

    # 验证结果 - UTC 14:30 应该转换为东八区 22:30
    expected_format = "2024-06-15 22:30:00"
    if serialized['created_at'] == expected_format:
        print("✅ 带时区时间转换成功！UTC 14:30:00 正确转换为东八区 22:30:00")
        return True
    else:
        print(f"❌ 带时区时间转换失败！期望: {expected_format}, 实际: {serialized['created_at']}")
        return False


if __name__ == "__main__":
    try:
        print("🚀 开始测试时区转换功能...\n")

        # 测试1: 无时区信息的datetime
        test1_result = test_timezone_conversion()

        # 测试2: 带时区信息的datetime
        test2_result = test_with_timezone_aware()

        # 总结结果
        print(f"\n📊 测试结果总结:")
        print(f"  测试1 (naive datetime): {'✅ 通过' if test1_result else '❌ 失败'}")
        print(f"  测试2 (aware datetime): {'✅ 通过' if test2_result else '❌ 失败'}")

        if test1_result and test2_result:
            print("\n🎉 所有测试通过！时区转换功能工作正常！")
        else:
            print("\n⚠️ 部分测试失败，请检查时区转换逻辑。")

    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()